<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import API from '@/services';
import AQueryHeader, { useQueryHeader } from '@dangojs/a-query-header';
import AQueryTable from '@dangojs/a-query-table';

import { Message, Modal } from '@arco-design/web-vue';
import Select from '@/arco-components/select/index.vue';
import { useRouter } from 'vue-router';
// import { MyCreateApprovalColumn } from '@/constants/approvalCenter'
// import CreateEditDrawer from '../createEditDrawer/index.vue'
import ArcoCustomColumn from '@/arco-components/arcoCustomColumn/index'
import ApprovalDrawer from '../approvalDrawer/index.vue'
import {myApproval, myApprovalColor} from '@/constants/approvalCenter'
import { ECustomColumn } from '@/utils/constants';
import _ from 'lodash'
import * as RouteNames from '@/router/consts';

const router = useRouter();
interface FormDataI {
  demandName: string | undefined;
  demandType: string | undefined;

  id: string | undefined;
  status: string | undefined;
  createBy: string | undefined;
}

const formData = reactive<FormDataI>({
  demandName: undefined,
  demandType: undefined,
  id: undefined,
  status: undefined,
  createBy: undefined
});

const querytableRef = ref<any>(null);
const loading = ref<boolean>(false)
const checkDraweRef = ref()
const createDrawerRef = ref()
//自定义列
const settings: any = ref([]);
//表格展示的字段
const newTableColumn: any = ref([]);
// 需求类型
  const demandTypeData: any = ref([]);
// 状态
const statusData: any = ref([
  { value: 'APPROVING', label: '待处理' },
  { value: 'APPROVED', label: '已处理' }
]);
/*创建人list*/
let userList: any = ref([]);

// 审批数据
const approvalData:any = ref()
/* 获取用户 */
const getUserList = async () => {
  try {
    const { code, data } = await API.demand.getUserList();
    if (code === 200 && Array.isArray(data)) {
      userList.value = data?.map((item:any) => {
        return {
          label: item.userName,
          value: item.userCode
        }
      });
    }
  } catch (error) {
    console.log(error);
  }
};
const getDemandTypeEnum = async () => {
  try {
    const { code, data } = await API.enumBao.getDemandTypeEnum({
      // type: EindexType.ATOMIC
    });
    if (code === 200 && Array.isArray(data)) {
      demandTypeData.value = data.map((item=> {
        return {
          label: item.value,
          value: item.key
        }
      }));
    }
  } catch (error) {
    console.log(error);
  }
};
const requestData = async (query: any) => {
  try {
    loading.value = true
    const res = await API.demand.postForUserPage(query);
    loading.value = false
    if (res.data) {
      return {
        success: true,
        data: res.data.list,
        total: Number(res.data.total)
      };
    }
    return {
      success: true,
      data: [],
      total: 0
    };
  } catch (e) {}
};
const { onReset,onSubmit, params } = useQueryHeader(formData, false);
const drawerTitle:any=ref()

// 审批
const onAudit = async (row: any) => {
    getCheckDetail(row, '审批')
}

// 查看审批
const onCheck = (row: any) => { 
    getCheckDetail(row, '查看审批')
}
// 审批
const editApi = async (id:any) => {
  try {
    const res = await API.demand.getGetDetailById({
      id
    });
    return res
  } catch (error) {
    console.warn(error);
  }
}
// 查看(分为指标类型为创建的需求 和 指标定义/下线/发布/删除”)
const getCheckDetail = async (row: any, text:string) => {
  // 判断需求审批和需求查看
  if (row.demandType === 'DEMAND') {
    const res = await editApi(row.id)
    if (res?.code === 200) {
      drawerTitle.value = text
      approvalData.value = res.data;
      checkDraweRef.value.visibleFn()
    }
  } else {
    try {
      router.push({
        name: RouteNames.ROUTER_APPROVAL_CENTER.ApprovalDetail,
        params: {
          id: row.id,
        },
        query: {
          type: text === '审批' ? 'approval' : 'check'
        }
      })
      
    } catch (error) {
      console.warn(error);
    }
  }
};
/* table Column */
    const tableColumn = ref([
      {
        title: "ID",
        dataIndex: "id",
        keys: 1,
        width: 100,
      },
      {
        title: "优先级",
        dataIndex: "priorityLevelDesc",
        keys: 5,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        keys: 7,
      },
      {
        title: '是否处理',
        keys: 8,
        dataIndex: 'operateStatus',
        slotRenderName: 'operateStatus',
      },
      {
        title: '操作',
        keys: 9,
        dataIndex: 'operater',
        slotRenderName: 'operater',
        fixed: 'right',
        width: 200
      }
    ]);

/* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.approval
        });
        if (code === 200) {
          settings.value = data?.settings.map((item:any) => {
            return {
              ...item,
              title: item.label,
              dataIndex: item.prop,
            }
          });

          const column = settings.value?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            let columnExtraParams:any = {
              ellipsis: true,
              tooltip: true,
            }
            if (v.keys === 3 || v.keys === 4) {
              Object.assign(v, columnExtraParams)
            }
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          
          newTableColumn.value = _.compact(column);
          newTableColumn.value = newTableColumn.value.filter((v: any) => v.isCheck)
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.approval,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          Message.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };
  const handleRefeash = () => {
    querytableRef.value.reload()
  }
  onMounted(() => {
    getDemandTypeEnum(); // 获取类型下拉数据
    getUserList(); // 获取创建人下拉列表数据
    getCustomColumnApi();
  });
</script>
<template>
  <div>
    <div class="mt-12 filter-search">
      <AQueryHeader @reset="onReset" @submit="onSubmit">
        <AFormItem show-colon label="需求ID">
          <AInput v-model="formData.id" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="类型">
          <Select v-model="formData.demandType" :options="demandTypeData" placeholder="请选择"></Select>
        </AFormItem>
        <AFormItem show-colon label="需求名称">
          <AInput v-model="formData.demandName" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="状态">
          <Select v-model="formData.status" :options="statusData" placeholder="请选择"></Select>
        </AFormItem>
        <AFormItem show-colon label="创建人">
          <Select 
            
            v-model="formData.createBy" 
            :options="userList" 
            placeholder="请选择创建人">
          </Select>
        </AFormItem>
      </AQueryHeader>
    </div>
    <a-divider />
    <div class="table-operate">
      <div class="CustomColumn-operate-wrap">
        <ArcoCustomColumn
          @confirm="(v: any) => customColumnConfirm(v)"
          :tableColumn="settings"
        />
      </div>
    </div>
    <AQueryTable
      ref="querytableRef"
      :columns="newTableColumn"
      :request="requestData"
      :params="params"
      :loading="loading"
      class="pblr-18"
    >
      <template #operateStatus="{ record }">
        <span v-if="record.operateStatus === 'PASSED' || record.operateStatus === 'REJECT'"> 
          <span class='dot col_24D'></span>
          <span>已处理</span>
        </span>
        <span v-else>
          <span class="dot col_FFA"></span>
          <span>待处理</span>
        </span>
      </template>

      <template #operater="{ record }">
        <a-button 
          type="text"
          v-if="record.operateStatus === 'PASSED' || record.operateStatus === 'REJECT'"
          @click="() => onCheck(record)">
          查看
        </a-button>
        <a-button 
          v-else
          type="text" 
          @click="() => onAudit(record)">
          审批
        </a-button>
      </template>
    </AQueryTable>
  </div>
  <ApprovalDrawer 
    type="approval"
    ref="checkDraweRef" 
    :checkDetail="approvalData"
    :drawerTitle="drawerTitle"
    @onReload="handleRefeash"
  />
  
</template>
<style lang="scss" scoped>

@import './index.scss';
</style>
